﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;

namespace MyLib
{
    static public class HexUtility
    {
        public static int HexToInt(this string hex)
        {
            int total = 0;
            for (int i = 0; i < hex.Length; i++)
            {
                int n = 0;
                if ((hex[i] >= '0') && (hex[i] <= '9'))
                    n = hex[i] - '0';
                else if ((hex[i] >= 'A') && (hex[i] <= 'F'))
                    n = hex[i] - 'A' + 10;
                else if ((hex[i] >= 'a') && (hex[i] <= 'f'))
                    n = hex[i] - 'a' + 10;
                else
                    throw new Exception("Invalid HEX string. '" + hex + "'");
                total = total * 16 + n;
            }
            return total;
        }

        public static byte HexToByte(this string hex)
        {
            return (byte)HexToInt(hex);
        }

        public static byte[] HexToBytes(this string hex)
        {
            Queue<byte> q = new Queue<byte>();
            string[] ss = hex.Split(new char[] { ' ', ',' });
            for (int i = 0; i < ss.Length; i++)
            {
                int pos = 0;
                while (pos < ss[i].Length)
                {
                    string s = "";
                    if (ss[i].Length - pos >= 2)
                    {
                        s = ss[i].Substring(pos, 2);
                        pos += 2;
                    }
                    else
                    {
                        s = ss[i].Substring(pos, ss[i].Length - pos);
                        pos += ss[i].Length - pos;
                    }
                    q.Enqueue(Convert.ToByte(HexToInt(s)));
                }
            }
            byte[] buffer = new byte[q.Count];
            int index = 0;
            while (q.Count > 0)
                buffer[index++] = q.Dequeue();
            return buffer;
        }

        public static string ByteToHex(byte b)
        {
            return b.ToString("X02");
        }

        public static string BytesToHex(byte[] buffer)
        {
            return BytesToHex(buffer, 0, buffer.Length);
        }

        public static string BytesToHex(byte[] buffer, int start, int count)
        {
            string s = "";
            for (int i = start; i < start + count; i++)
                if (i == start)
                    s = buffer[i].ToString("X02");
                else
                    s = s + " " + buffer[i].ToString("X02");
            return s;
        }

    }
}
